﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using WikiDoc.Formatter;
using WikiDoc.Lines;
using WikiDoc.Utils;

namespace WikiDoc.Parser
{
    /// <summary>
    /// 解析列表
    /// </summary>
    public class DefineListParser
    {
        public void Process(WikiReader reader, IFormatter formatter)
        {
            ParseList(reader, formatter);
        }

        /// <summary>
        /// 读取一个完整的列表，直到列表结束，退出时当前行是下一个片段起始行
        /// </summary>
        /// <param name="reader">The reader.</param>
        /// <param name="formatter">The formatter.</param>
        private static void ParseList(WikiReader reader, IFormatter formatter)
        {
            if (reader.CurrentLine.Type != LineTypes.DefineList)
            {
                return;
            }

            var started = false;
            var keepgo = true;

            formatter.BeginTag("dl");

            while (keepgo)
            {
                switch (reader.CurrentLine.Type)
                {
                    case LineTypes.DefineList:
                        if (started) formatter.EndTag("dd");

                        var line = (DefineListLine) reader.CurrentLine;

                        formatter.BeginTag("dt");
                        formatter.AppendContent(line.Name);
                        formatter.EndTag("dt");
                        formatter.BeginTag("dd");
                        formatter.AppendContent(line.Content);
                        started = true;
                        reader.ReadLine();

                        break;

                    // 一个空行表示一个列表项的结束
                    case LineTypes.Empty:
                        if (started) formatter.EndTag("dd");
                        started = false;

                        // 跳过后续的所有空行
                        do
                        {
                            formatter.BeginTag("br");
                            formatter.EndTag("br");
                            reader.ReadLine();
                        } while (reader.CurrentLine.Type == LineTypes.Empty);

                        break;
                        
                        // 列表中遇到普通行或缩进行视为续行
                    case LineTypes.Indent:
                        formatter.AppendContent(reader.CurrentLine.Line);
                        reader.ReadLine();
                        break;

                    // 其他情况，视为列表结束
                    default:
                        if (started) formatter.EndTag("dd");
                        keepgo = false;
                        break;
                }

            }

            formatter.EndTag("dl");
        }
    }
}
